<?php
/**
 * 导出销量报表（已弃用）
 */
namespace App\Admin\Controllers\SalesReport;

use App\Jobs\SalesReport\CreateSVEFile;
use App\Mail\SalesReport\SVEFile;
use App\Models\SalesReport\SVExportFile;
use App\Util\User;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Form;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Request;
class SVExportController extends AdminController{

    protected $title = '导出销量报表';

    protected $filters = [
        'start_date' => null,
        'end_date' => null,
//        'file_type' => null,
    ];

    protected function grid()
    {
        $filtersField = array_keys($this->filters);
        $filters = $this->_getFilters($filtersField);
        $this->_initFilters($filters);
        $query = $this->_initQuery($filters);
        $paginator = $this->_paginator($query);
        $action = getAction($filtersField);
        $filtersBlade = [];
        $filtersBlade['start_date'] = $this->filters['start_date'];
        $filtersBlade['end_date'] = $this->filters['end_date'];
//        $filtersBlade['file_type'] = getOptions(SVExportFile::$_fileType,$this->filters['file_type']);
        return view('sales-report.sv-export.index', compact('paginator','filtersBlade','action'));
    }

    private function _getFilters($filtersField){
        $filters = [];
        foreach ($filtersField as $field){
            $filters[$field] = request($field);
        }
        return $filters;
    }

    private function _initFilters($filters){
        foreach ($filters as $field => $filter){
            $this->filters[$field] = $filter;
        }
    }

    private function _initQuery($filters){
        $query = SVExportFile::query()->orderBy('id','DESC');
        foreach ($filters as $field => $filter){
            if(!$filter)continue;
            if($field == 'start_date'){
                $query->where('start_date','>=',$filter);
            }
            if($field == 'end_date'){
                $query->where('end_date','<=',$filter);
            }
            if(in_array($field,['file_type'])){
                $query->where($field,$filter);
            }
        }
        return $query;
    }

    private function _paginator($query){
        return $query->paginate((int) (request("per_page",10)))->appends(Request::input());
    }

    public function download(){
        $id = request('id');
        $f = SVExportFile::query()->find($id);
        if(!$f) {
            admin_toastr('无文件记录！','error');
            return back();
        }
        try{
            $fileDir = SVExportFile::fileDir($f->file_type);
            $file = public_uploads_path($fileDir).DIRECTORY_SEPARATOR.$f->file_name;
            if(!file_exists($file)){
                admin_toastr('无文件！','error');
                return back();
            }
            return response()->download($file);
        }catch (\Exception $e){
            report($e);
            admin_toastr('操作失败！','error');
            return back();
        }
    }

    public function form()
    {
        return new Form(new SVExportFile());
    }

    protected function exportFile(){
        try{
            $userId = Admin::user()->id;
            $email = User::getEmailById($userId);
            if(!$email){
                return response()->json(['status' => false,'message' => '请在用户列表添加合法的邮件地址！']);
            }
            $param = request('param');
            $file = SVExportFile::getFile($param['file_type'],$param['start_date'],$param['end_date']);
            DB::beginTransaction();
            $model = SVExportFile::query()->firstOrNew([
                'start_date' => $param['start_date'],
                'end_date' => $param['end_date'],
                'file_type' => $param['file_type']
            ]);
            if(!$model){
                DB::rollBack();
                return response()->json(['status' => false,'message' => '文件创建失败!']);
            }
            $model->file_name = basename($file);
            $model->user_id = $userId;
            $flag = $model->save();
            if($flag){
                DB::commit();
            }else{
                DB::rollBack();
                return response()->json(['status' => true,'message' => '文件添加失败！']);
            }
            if(file_exists($file)){
//                Mail::to($email)->send(new SVEFile($file));
                return response()->json(['status' => true,'message' => '报表已生成！']);
            }else{
                //销量报表
                CreateSVEFile::dispatch($model);
                return response()->json(['status' => true,'message' => '报表正在生成，请稍后查看！']);
            }
        }catch (\Exception $e){
            report($e);
            return response()->json(['status' => false, 'message' => '系统异常！']);
        }
    }
}
